package com.linkwedo.saas.member;

import javax.servlet.http.Cookie;

import org.apache.struts2.ServletActionContext;

import com.linkwedo.saas.directory.LDAPService;
import com.linkwedo.saas.support.BaseAction;
import com.linkwedo.saas.support.Security;
import com.sun.org.apache.xml.internal.security.utils.Base64;

public class ToLoginAction extends BaseAction {
	private static final long serialVersionUID = 8190003683775267839L;

	public String execute() throws Exception {

		String email = null, userDN = null;

		boolean emailCookieExist = false;
		Cookie[] cookies = ServletActionContext.getRequest().getCookies();
		for (Cookie cookie : cookies) {
			if (cookie.getName().equals("el")) {
				emailCookieExist = true;
				String value = cookie.getValue();
				byte[] bytes = Security.symmetryDecrypt(Base64.decode(value));
				email = new String(bytes, "UTF-8");
				break;
			}
		}

		if (!emailCookieExist) {
			return LOGIN;
		}

		userDN = LDAPService.getUserDN(email);
		if (userDN == null) {
			return LOGIN;
		}
		
		LoginService.doLoginWork(email ,userDN, getApplication(), getSession());
		
		return SUCCESS;
	}
}
